<?php

namespace App\Http\Services;

use App\Exceptions\ServiceException;
use App\Exceptions\ServiceExceptionConstant;
use App\Http\Repositories\Daos\Campus\CampusDao;
use App\Http\Repositories\Daos\Course\CourseDao;
use App\Http\Requests\UserContext;
use App\Http\Traits\Errors;
use App\Http\Traits\GlobalConstant;
use App\Models\Absence;
use App\Models\Banner;
use App\Models\Category;
use App\Models\Course;
use App\Models\CourseDuty;
use App\Models\CourseDutyTeacher;
use App\Models\CourseOrder;
use App\Models\CourseSection;
use App\Models\Leave;
use App\Models\Mutual;
use App\Models\MutualRecord;
use App\Models\Recommend;
use App\Models\Users;
use App\Models\UserScoreRecord;
use App\Models\Video;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CourseService extends BaseService
{
    use Errors;

    protected $courseDao;
    protected $campusDao;

    public function __construct(CourseDao $courseDao, CampusDao $campusDao)
    {
        $this->courseDao = $courseDao;
        $this->campusDao = $campusDao;
    }

    public function campusCourseLists()
    {
        $campusId = request('campus_id') ?? 0;
        if (empty($campusId)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('校区不存在'));
        }
//        $condition = [
//            'status'    => 1,
//            'campus_id' => $campusId
//        ];

        $campus_info = $this->campusDao->getOne(['id' => $campusId, 'status' => 1], [], ['id', 'name', 'contact', 'logo', 'longitude', 'latitude', 'address', 'line_pics', 'room_pics']);
        if (empty($campus_info)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('校区不存在'));
        }
//        $page   = request('page') ?? 1;
//        $size   = request('size') ?? 10;
//        $field  = ['*'];
//        $offset = ($page * $size) - $size;
//        $list   = Recommend::where($condition)->limit($size)->offset($offset)->orderBy('created_at', 'desc')->get($field);
        return compact("campus_info");
    }

    public function lists()
    {
        $campusId  = request('campus_id') ?? 0;
        $keyword   = request('key_word') ?? '';
        $lat       = request('lat') ?? 0;
        $lng       = request('lng') ?? 0;
        $condition = [
            'valid' => 1,
        ];
        if (!empty($campusId)) {
            $condition['campus_id'] = $campusId;
        }
//        if (!empty($keyword)) {
//            $condition[] = ['name', 'like', '%' . $keyword . '%'];
//        }
        $page   = request('page') ?? 1;
        $size   = request('size') ?? 10;
        $field  = ['id', 'campus_id', 'name', 'score', 'start_time', 'class_time', 'discover', 'video_url', 'intro', 'price', 'total', 'read_num', 'is_sug', 'valid', 'tips', 'pics', 'desc', 'reflex'];
        $offset = ($page * $size) - $size;
        $q      = $this->courseDao->getModel()->where($condition);
        if (!empty($keyword)) {
            $q = $q->whereRaw("(course.name like ? or `desc` like ? or teacher_id in (select id from teacher where name like ?) or course.id in (select course_id from course_section where name like ?))", ["%{$keyword}%", "%{$keyword}%", "%{$keyword}%", "%{$keyword}%"]);
        }
        $list = $q->join('campus', 'course.campus_id', '=', 'campus.id')
            ->select(DB::raw("course.*, campus.name as campus_name, contact,logo,longitude,latitude,address,(6371 * acos(cos(radians(latitude)) * cos(radians($lat)) * cos(radians(longitude) - radians($lng)) + sin(radians(latitude)) * sin(radians($lat))))*1000 AS distance"))
            ->withCount('courseSectionInfo')->limit($size)->offset($offset)->orderBy('distance', 'asc')->orderBy('start_time', 'asc')->get($field);
        if (!empty($lat) && !empty($lng) && !empty($list)) {//有距离显示时转换距离
            foreach ($list as &$item) {
                $lastInfo  = DB::table('course_section')->where('course_id', $item['id'])->orderBy('end_time', 'desc')->first();
                $firstInfo = DB::table('course_section')->where('course_id', $item['id'])->orderBy('begin_time', 'asc')->first();
                if ($firstInfo && $lastInfo) {
                    if ($item['is_cancel'] == 1) {
                        $item['background'] = 'rgba(0,0,0,0.5)';
                        $item['status_tag'] = '已取消';
                    } elseif (time() > $lastInfo->end_time) {
                        $item['background'] = 'rgba(0,0,0,0.5)';
                        $item['status_tag'] = '已结束';
                    } elseif (time() < $lastInfo->end_time && time() > $firstInfo->begin_time) {
                        $item['background'] = 'rgba(1,145,255,0.5)';
                        $item['status_tag'] = '进行中';
                    } else {
                        $item['status_tag'] = '待开课';
                        $item['background'] = 'rgba(247,181,1,0.5)';
                    }
                } else {
                    $item['background'] = 'rgba(0,0,0,0.5)';
                    $item['status_tag'] = '已结束';
                }
                $item['score']    = $item['score'] * $item['course_section_info_count'];
                $item['distance'] = $item->distance >= 1000 ? round($item->distance / 1000, 1) . "km" : ceil($item->distance) . "m";
            }
            unset($item);
        }
        return compact("list");
    }

    public function detail()
    {
        $detailId = request('c_id') ?? 0;
        $detail   = $this->courseDao->getModel()->where(['id' => $detailId, 'valid' => 1])->with(["campusInfo" => function ($query) {
            $query->select(['id', 'name', 'contact', 'logo', 'longitude', 'latitude', 'address']);
        }, "courseSectionInfo"                                                                                 => function ($query) {
            $query->select(['id', 'course_id', 'name', 'serial_number', 'class_time', 'begin_time', 'end_time']);
        }, "teacherInfo"                                                                                       => function ($query) {
            $query->select(['id', 'name', 'avatar', 'intro', 'sex', 'age', 'edu_max', 'mobile']);
        }])->withCount('courseSectionInfo')->first();
        if (!$detail) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('课程不存在'));
        }
        $introLen = mb_strlen($detail['intro']);
//        $detail['long_intro'] = $detail['intro'] . '...收起';
        $detail['long_intro'] = $detail['intro'];
        $detail['str_length'] = $introLen;
        if ($introLen > 39) {
//            $detail['intro'] = mb_substr($detail['intro'], 0, 39) . '...展开';
            $detail['intro'] = mb_substr($detail['intro'], 0, 39);
        }

        return $detail;
    }

    public function categoryLists()
    {
//        $field = ['id as value', 'name as text'];
//        return Category::where('status', 1)->get($field);
        $field = ['id', 'name'];
        return Category::where('status', 1)->get($field)->map(function ($item) {
            return ['id' => (string)$item['id'], 'name' => $item['name']];
        });

    }

    public function monthOrWeek()
    {
        $type     = request('t') ?? 'm';
        $startDay = (int)date('d');
        $year     = request('y') ?? date('Y');
        $endDay   = 0;
        $sql      = 'COUNT(*) as num,';
        switch ($type) {
            case 'w':
                $sql          .= "DATE_FORMAT( FROM_UNIXTIME( start_time ), '%Y-%m-%d' ) as _val";
                $month        = (int)request('mon');
                $currentMonth = (int)date('m');
//                $year         = date('Y');
                $endDay    = (int)date('t', strtotime("$year-$month-01"));//需要查询的月份的最后一天
                $timeBegin = strtotime(date('Y-m-d 00:00:00'));
                if ($currentMonth != $month) {
                    $startDay  = 1;
                    $timeBegin = strtotime(date("Y-$month-1 00:00:00"));
                }
                $timeEnd = strtotime(date("Y-$month-$endDay 23:59:59"));
                break;
            default:
                $sql .= "MONTH(FROM_UNIXTIME(start_time)) as _val";
//                $timeBegin = strtotime(date('Y-m-d 00:00:00'));
//                $timeEnd   = strtotime(date('Y-12-31 23:59:59'));
                $timeBegin = strtotime(date("$year-1-1 00:00:00"));
                $timeEnd   = strtotime(date("$year-12-31 23:59:59"));

                break;
        }
        $list = DB::table('course')->selectRaw($sql)
            ->where('start_time', ">=", $timeBegin)
            ->where('start_time', '<', $timeEnd)
            ->where('valid', 1)
            ->whereNull('deleted_at')
            ->groupBy("_val")->get()->toArray();
//        $demo = $this->courseDao->getListPage(['valid'=>1],['id','name','created_at'],1,100,['created_at'=>'asc']);
//        return $demo;
//        return $list;
        if ($type == 'w') {
            return self::formatWeekData($list, $month, $startDay, $endDay);
        }
        return self::formatMonthData($list);
    }

    protected static function formatMonthData($list)
    {
//        dd($list);
        $currentMonth = (int)date('m');
        $newList      = [];
        foreach ($list as $item) {
            $newList[$item->_val] = $item->num;
        }
        $arr = [];
        for ($i = 1; $i <= 12; $i++) {
            $data['title'] = $i . '月';
            if (!array_key_exists($i, $newList)) {
                $data['content'] = '0个课程';
            } else {
                $data['content'] = $newList[$i] . '个课程';
            }
            $data['val']   = $i;
            $data['check'] = 2;
            $arr[]         = $data;
        }
        return $arr;
    }

    protected static function formatWeekData($list, $month, $startDay, $endDay)
    {
//        dd($month,$startDay,$endDay,$list);
        $newList = [];
        if (!empty($list)) {
            foreach ($list as $item) {
                $newList[strtotime($item->_val)] = $item->num;
            }
        }

        $group = self::generateGroups($newList, $month, $startDay, $endDay);
        foreach ($group as $item) {
            $title = current($item)['day'] . '日';
            $val   = current($item)['day'];
            if (count($item) > 1) {
                $start = current($item)['day'];
                $end   = end($item)['day'];
                $title = $start . '日-' . $end . '日';
                $val   = $start . ',' . $end;
            }
            $data['title']   = $title;
            $data['content'] = array_sum(array_column($item, 'val')) . '个课程';
            $data['val']     = $val;
            $data['check']   = 2;
            $arr[]           = $data;
            unset($data);
        }
        return $arr;
    }

    public static function generateGroups($list, $month, $startDay, $endDay)
    {
        $groups = array();
        $group  = array();
        $total  = 0;
//        dd($list);
        for ($i = $startDay; $i <= $endDay; $i++) {
            $temp = strtotime(date("Y-$month-$i"));
            if (!empty($list)) {
                foreach ($list as $key => $item) {
                    if ($key == $temp) {
                        $total += $item;
                        break;
                    }
                }
            }

            $group[] = ['day' => $i, 'val' => $total];
            $total   = 0;
            // 如果当前循环次数是7的倍数，将当前组添加到总数组，并重置组
            if (count($group) % 7 == 0) {
                $groups[] = $group;
                $group    = array();
            }
        }

        // 如果最后一个组不满7个元素，将其添加到总数组
        if (!empty($group)) {
            $groups[] = $group;
        }
//        dd($groups);
        return $groups;
    }

    public function listWithTime()
    {
        $type      = request('t') ?? 'm';
        $year      = request('y') ?? date('Y');
        $month     = request('mon');
        $week      = request('week');
        $lat       = request('lat') ?? 0;
        $lng       = request('lng') ?? 0;
        $condition = [
            'valid' => 1,
        ];
        switch ($type) {
            case 'm':
                $startTime = strtotime(date("$year-$month-1") . ' 00:00:00');
//                $currentMonth = date('m');
//                if ((int)$currentMonth == $month) {//如果月份加载的是当前月，则从当前时间算否则算1-查询月的最后一天，比如当前是5月27且查询的是5月，则5月27以前的不算
//                    $currentDay = date('d');
//                    $startTime  = strtotime(date("Y-$month-$currentDay") . ' 00:00:00');
//                }
                $endDay = date('t', strtotime("$year-$month-01"));
//                $endTime = strtotime(date("Y-$month-$endDay") . ' 23:59:59');
                $endTime = strtotime(date("$year-$month-$endDay") . ' 23:59:59');
                break;
            default:
                $dateArray = explode(GlobalConstant::DELIMITER_CHARACTER, $week);
                if (count($dateArray) == 1) {
                    $startTime = strtotime(date("Y-$month-$dateArray[0]") . ' 00:00:00');
                    $endTime   = strtotime(date("Y-$month-$dateArray[0]") . ' 23:59:59');
                } else {
                    $startTime = strtotime(date("Y-$month-$dateArray[0]") . ' 00:00:00');
                    $endTime   = strtotime(date("Y-$month-$dateArray[1]") . ' 23:59:59');
                }
                break;
        }
        $condition[] = ['start_time', '>=', $startTime];
        $condition[] = ['start_time', '<=', $endTime];
        $page        = request('page') ?? 1;
        $size        = request('size') ?? 10;
        $field       = ['*'];
        $offset      = ($page * $size) - $size;
//        $list        = $this->courseDao->getModel()->where($condition)->with(["campusInfo" => function ($query) use ($lat, $lng) {
//            $query->select(DB::raw("id, name,contact,logo,longitude,latitude,address,(6371 * acos(cos(radians(latitude)) * cos(radians($lat)) * cos(radians(longitude) - radians($lng)) + sin(radians(latitude)) * sin(radians($lat))))*1000 AS distance"));
//        }])->withCount('courseSectionInfo')->limit($size)->offset($offset)->orderBy('start_time', 'desc')->get($field);
//        if ($list) {
//            foreach ($list as &$item) {
//                $item['distance'] = $item->campusInfo->distance >= 1000 ? round($item->campusInfo->distance / 1000, 1) . "km" : ceil($item->campusInfo->distance) . "m";
//            }
//            unset($item);
//        }
        $list = Course::where($condition)->join('campus', 'course.campus_id', '=', 'campus.id')
            ->select(DB::raw("course.*, campus.name as campus_name, contact,logo,longitude,latitude,address,(6371 * acos(cos(radians(latitude)) * cos(radians($lat)) * cos(radians(longitude) - radians($lng)) + sin(radians(latitude)) * sin(radians($lat))))*1000 AS distance"))
            ->withCount('courseSectionInfo')->limit($size)->offset($offset)->orderBy('distance')->orderBy('start_time', 'asc')->get();
        if (!empty($list)) {//有距离显示时转换距离
            foreach ($list as &$item) {
                $lastInfo  = DB::table('course_section')->where('course_id', $item['id'])->orderBy('end_time', 'desc')->first();
                $firstInfo = DB::table('course_section')->where('course_id', $item['id'])->orderBy('begin_time', 'asc')->first();
                if ($firstInfo && $lastInfo) {
                    if ($item['is_cancel'] == 1) {
                        $item['background'] = 'rgba(0,0,0,0.5)';
                        $item['status_tag'] = '已取消';
                    } elseif (time() > $lastInfo->end_time) {
                        $item['background'] = 'rgba(0,0,0,0.5)';
                        $item['status_tag'] = '已结束';
                    } elseif (time() < $lastInfo->end_time && time() > $firstInfo->begin_time) {
                        $item['background'] = 'rgba(1,145,255,0.5)';
                        $item['status_tag'] = '进行中';
                    } else {
                        $item['status_tag'] = '待开课';
                        $item['background'] = 'rgba(247,181,1,0.5)';
                    }
                } else {
                    $item['background'] = 'rgba(0,0,0,0.5)';
                    $item['status_tag'] = '已结束';
                }


                $item['score']    = $item['score'] * $item['course_section_info_count'];
                $item['distance'] = $item->distance >= 1000 ? round($item->distance / 1000, 1) . "km" : ceil($item->distance) . "m";
            }
            unset($item);
        }
        return $list;
    }

    public function listWithTime2()
    {
        $type      = request('t') ?? 'm';
        $month     = request('mon');
        $week      = request('week');
        $lat       = request('lat') ?? 0;
        $lng       = request('lng') ?? 0;
        $condition = [
            'valid' => 1,
        ];
        switch ($type) {
            case 'm':
                $startTime    = strtotime(date("Y-$month-1") . ' 00:00:00');
                $currentMonth = date('m');
                if ((int)$currentMonth == $month) {//如果月份加载的是当前月，则从当前时间算否则算1-查询月的最后一天，比如当前是5月27且查询的是5月，则5月27以前的不算
                    $currentDay = date('d');
                    $startTime  = strtotime(date("Y-$month-$currentDay") . ' 00:00:00');
                }
                $year    = date('Y');
                $endDay  = date('t', strtotime("$year-$month-01"));
                $endTime = strtotime(date("Y-$month-$endDay") . ' 23:59:59');
                Log::info('加载的是月份' . date('Y-m-d', $startTime) . ' ' . date('Y-m-d', $endTime));
                break;
            default:
                $dateArray = explode(GlobalConstant::DELIMITER_CHARACTER, $week);
//                dd($dateArray);
                if (count($dateArray) == 1) {
                    $startTime = strtotime(date("Y-$month-$dateArray[0]") . ' 00:00:00');
                    $endTime   = strtotime(date("Y-$month-$dateArray[0]") . ' 23:59:59');
                } else {
                    $startTime = strtotime(date("Y-$month-$dateArray[0]") . ' 00:00:00');
                    $endTime   = strtotime(date("Y-$month-$dateArray[1]") . ' 23:59:59');
                }
                Log::info('加载的是周' . date('Y-m-d', $startTime) . ' ' . date('Y-m-d', $endTime));
                break;
        }
        $condition[] = ['start_time', '>=', $startTime];
        $condition[] = ['start_time', '<=', $endTime];
        $page        = request('page') ?? 1;
        $size        = request('size') ?? 10;
        $field       = ['*'];
        $offset      = ($page * $size) - $size;
        $list        = $this->courseDao->getModel()->where($condition)->with(["campusInfo" => function ($query) use ($lat, $lng) {
            $query->select(DB::raw("id, name,contact,logo,longitude,latitude,address,(6371 * acos(cos(radians(latitude)) * cos(radians($lat)) * cos(radians(longitude) - radians($lng)) + sin(radians(latitude)) * sin(radians($lat))))*1000 AS distance"));
        }])->withCount('courseSectionInfo')->limit($size)->offset($offset)->orderBy('start_time', 'desc')->get($field);
        if ($list) {
            foreach ($list as &$item) {
                $item['distance'] = $item->campusInfo->distance >= 1000 ? round($item->campusInfo->distance / 1000, 1) . "km" : ceil($item->campusInfo->distance) . "m";
            }
            unset($item);
        }
        return $list;
    }

    public function sign(UserContext $userContext)
    {
        $userId     = $userContext->getId();
        $teacherId  = $userContext->getTeacherId();
        $courseId   = request('c_id') ?? 0;
        $sectionId  = request('s_id') ?? 0;
        $signStatus = request('sign_status') ?? 1;
        $signType   = request('sign_type') ?? 1;
        $role       = request('role') ?? 0;
        if (empty($courseId)) $this->showError('请选择课程');
        if (empty($sectionId)) $this->showError('请选择章节');
        if (empty($role)) $this->showError('身份信息异常');
        if ($role == 1) {
            $info = CourseDutyTeacher::where('course_id', $courseId)->where('teacher_id', $teacherId)->where('sign_type', $signType)->where('course_section_id', $sectionId)->where('sign_type', $signType)->first();
            if ($info) $this->showError('请勿重复签到');
            CourseDutyTeacher::create([
                'teacher_id'        => $teacherId,
                'course_id'         => $courseId,
                'course_section_id' => $sectionId,
                'sign_status'       => $signStatus,
                'sign_type'         => $signType,
                'sign_time'         => time()
            ]);
            Artisan::call('sign:score');
            return true;
        }
        if ($role == 2 || $role == 3) {//学生和商家用一个表
            $orderInfo = CourseOrder::where('user_id', $userId)->where('course_id', $courseId)->first();
            if (!$orderInfo) $this->showError('当前报名不存在');
            $courseSectionCount = CourseSection::where('course_id', $courseId)->where('status', 1)->count();
            $half               = intval(ceil($courseSectionCount / 2));
            if ($orderInfo['leave'] >= $half) $this->showError('该课请假超过50%，不能再上该课');
            $info = CourseDuty::where('course_id', $courseId)->where('user_id', $userId)->where('sign_type', $signType)->where('course_section_id', $sectionId)->where('sign_type', $signType)->first();
            if ($info) $this->showError('请勿重复签到');
            CourseDuty::create([
                'user_id'           => $userId,
                'course_id'         => $courseId,
                'course_section_id' => $sectionId,
                'sign_status'       => $signStatus,
                'sign_type'         => $signType,
                'sign_time'         => time()
            ]);
            Artisan::call('sign:score');
            return true;
        }

    }

    public function gateStatics(UserContext $userContext)
    {
        $userId   = $userContext->getId();
        $courseId = request('course_id') ?? 0;
        if (empty($courseId)) {
            $had     = CourseDuty::where('user_id', $userId)->count();
            $leave   = Leave::where('user_id', $userId)->count();
            $absence = Absence::where('user_id', $userId)->count();
//            $total    = CourseSection::whereIn('course_id', function ($query) use ($userId) {
//                $query->where('user_id', $userId)->where(function ($q) {
//                    $q->where('status', 2)->orwhere('status', 3);
//                })->select('course_id')->from('course_order');
//            })->count();
//            $future   = CourseSection::join('course_order', 'course_order.course_id', '=', 'course_section.course_id')
//                ->where('user_id', $userId)->where('course_order.status', 2)->where('end_time', '>=', time() - 15 * 60)
//                ->where('course_section.status', 1)->count();//再查所有未到上课的章节
//            $ll_leave = CourseOrder::where('user_id', $userId)->where('status', 2)->sum('leave');
        } else {

            $had     = CourseDuty::where('user_id', $userId)->where('course_id', $courseId)->count();
            $leave   = Leave::where('user_id', $userId)->where('course_id', $courseId)->count();
            $absence = Absence::where('user_id', $userId)->where('course_id', $courseId)->count();
//            $total    = CourseSection::whereIn('course_id', function ($query) use ($userId, $courseId) {
//                $query->where('user_id', $userId)->where(function ($q) {
//                    $q->where('status', 2)->orwhere('status', 3);
//                })->select('course_id')->where('course_id', $courseId)->from('course_order');
//            })->where('course_id', $courseId)->count();
//            $future   = CourseSection::join('course_order', 'course_order.course_id', '=', 'course_section.course_id')
//                ->where('user_id', $userId)->where('course_order.status', 2)->where('end_time', '>=', time() - 15 * 60)
//                ->where('course_section.course_id', $courseId)->where('course_section.status', 1)->count();//再查所有未到上课的章节
//            $ll_leave = CourseOrder::where('user_id', $userId)->where('status', 2)->where('course_id', $courseId)->sum('leave');
        }
        return compact("had", "leave", "absence");
    }

    public function gateStatics2(UserContext $userContext)
    {
        $userId   = $userContext->getId();
        $courseId = request('course_id') ?? 0;
        if (empty($courseId)) {
            $res    = DB::select('SELECT

                          COUNT(*) AS had
                        FROM
                          (SELECT
                            course_section_id,
                            COUNT(DISTINCT sign_type) AS sign_types
                          FROM
                            course_duty
                          WHERE sign_type IN (1, 2) and user_id =?
                          GROUP BY course_section_id, user_id
                          HAVING sign_types = 2) AS subquery', [$userId]);
            $total  = CourseSection::whereIn('course_id', function ($query) use ($userId) {
                $query->where('user_id', $userId)->where(function ($q) {
                    $q->where('status', 2)->orwhere('status', 3);
                })->select('course_id')->from('course_order');
            })->count();
            $future = CourseSection::join('course_order', 'course_order.course_id', '=', 'course_section.course_id')->where('user_id', $userId)->where('course_order.status', 2)->where('begin_time', '>=', time())->where('course_section.status', 1)->count();//再查所有未到上课的章节
        } else {
            $res    = DB::select('SELECT

                          COUNT(*) AS had
                        FROM
                          (SELECT
                            course_section_id,
                            COUNT(DISTINCT sign_type) AS sign_types
                          FROM
                            course_duty
                          WHERE sign_type IN (1, 2) and user_id =? and course_id=?
                          GROUP BY course_section_id, user_id
                          HAVING sign_types = 2) AS subquery', [$userId, $courseId]);
            $total  = CourseSection::whereIn('course_id', function ($query) use ($userId, $courseId) {
                $query->where('user_id', $userId)->where(function ($q) {
                    $q->where('status', 2)->orwhere('status', 3);
                })->select('course_id')->where('course_id', $courseId)->from('course_order');
            })->where('course_id', $courseId)->count();
            $future = CourseSection::join('course_order', 'course_order.course_id', '=', 'course_section.course_id')->where('user_id', $userId)->where('course_order.status', 2)->where('begin_time', '>=', time())->where('course_section.course_id', $courseId)->where('course_section.status', 1)->count();//再查所有未到上课的章节
        }

        $had = $res[0]->had;
        return compact("total", "had", "future");
    }

    public function giveScore(UserContext $userContext)
    {
        $userId      = $userContext->getId();
        $recommendId = request('r_id') ?? 0;
        $mutual      = json_decode(request('mutual') ?? '', true);
        if (empty($mutual)) return true;
        $exist = MutualRecord::where('user_id', $userId)->where('recommend_id', $recommendId)->first();
        if (!empty($exist)) $this->showError('您已经领取过了');
        $mutualIds  = array_column($mutual, 'id');
        $mutualList = Mutual::whereIn('id', $mutualIds)->get()->toArray();
        if (empty($mutualList)) {
            return true;
        }
        $score = 0;
        foreach ($mutual as $item) {
            $data['recommend_id'] = $recommendId;
            $data['user_id']      = $userId;
            $data['mutual_id']    = $item['id'];
            $data['answer']       = $item['answer'];
            $data['created_at']   = time();
            $data['updated_at']   = time();
            $arr[]                = $data;
            foreach ($mutualList as $value) {
                if ($item['id'] == $value['id'] && $value['right_answer'] == $item['answer']) {
                    $score += $value['score'];
                }
            }
        }

        DB::beginTransaction();
        try {
            $res  = DB::table('mutual_record')->insert($arr);
            $flag = true;
            if ($score > 0) {
                $remark = '观看视频获得积分' . $score;
                $flag   = UserScoreRecord::create(['user_id' => $userId, 'qty' => $score, 'remark' => $remark]);
            }
            if ($score > 0 && $res && $flag) {
                Users::where('id', $userId)->increment('score', $score);
            }
            DB::commit();
            return true;

        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error('看视频回答获取积分异常' . $exception->getMessage());
            return false;
        }

    }

    public function waterList2()
    {
        $keyword   = request('key_word') ?? '';
        $lat       = request('lat') ?? 0;
        $lng       = request('lng') ?? 0;
        $condition = [
            'recommend.status' => 1,
        ];
        if (!empty($keyword)) {
            $condition[] = ['recommend.title', 'like', '%' . $keyword . '%'];
        }
        $page   = request('page') ?? 1;
        $size   = request('size') ?? 10;
        $offset = ($page * $size) - $size;
        $list   = Recommend::where($condition)->join('campus', 'recommend.campus_id', '=', 'campus.id')
            ->select(DB::raw("recommend.*, campus.name as campus_name, contact,logo,longitude,latitude,address,(6371 * acos(cos(radians(latitude)) * cos(radians($lat)) * cos(radians(longitude) - radians($lng)) + sin(radians(latitude)) * sin(radians($lat))))*1000 AS distance"))
            ->limit($size)->offset($offset)->having('distance', '>', 0)->orderBy('distance', 'asc')->orderBy('campus_id', 'asc')->get();

        $total = Recommend::where($condition)->count();
        if (!empty($list)) {//有距离显示时转换距离
            foreach ($list as &$item) {
                $item['score']    = $item->mutual->sum('score');
                $item['distance'] = $item->distance >= 1000 ? round($item->distance / 1000, 1) . "km" : ceil($item->distance) . "m";
            }
            unset($item);
        }
        return compact("list", "total");
    }

    public function waterList()
    {
        $keyword   = request('key_word') ?? '';
        $lat       = request('lat') ?? 0;
        $lng       = request('lng') ?? 0;
        $condition = [
            'video.status' => 1,
        ];
//        if (!empty($keyword)) {
//            $condition[] = ['video.title', 'like', '%' . $keyword . '%'];
//        }
        $page   = request('page') ?? 1;
        $size   = request('size') ?? 10;
        $offset = ($page * $size) - $size;
        $query1 = Video::where($condition)->join('campus', 'video.campus_id', '=', 'campus.id');
        if (!empty($keyword)) {
            $query1 = $query1->whereRaw("(video.title like '%$keyword%' or campus.name like '%$keyword%' or video.desc like '%$keyword%')");
        }
        $list = $query1->select(DB::raw("video.title,video.id,pics,video_url,read_num, campus.name as campus_name, contact,logo,longitude,latitude,address,(6371 * acos(cos(radians(latitude)) * cos(radians($lat)) * cos(radians(longitude) - radians($lng)) + sin(radians(latitude)) * sin(radians($lat))))*1000 AS distance"))
            ->limit($size)->offset($offset)->having('distance', '>', 0)->orderBy('distance', 'asc')->orderBy('campus_id', 'asc')->get();

        $query2 = Video::where($condition)->join('campus', 'video.campus_id', '=', 'campus.id');
        if (!empty($keyword)) {
            $query2 = $query2->whereRaw("(video.title like '%$keyword%' or campus.name like '%$keyword%' or video.desc like '%$keyword%')");
        }
        $total = $query2->count();
        if (!empty($list)) {//有距离显示时转换距离
            foreach ($list as &$item) {
                $item['distance'] = $item->distance >= 1000 ? round($item->distance / 1000, 1) . "km" : ceil($item->distance) . "m";
            }
            unset($item);
        }
        return compact("list", "total");
    }

    public function recommendDetail()
    {
        $recommendId = request('r_id') ?? 0;
        $detail      = Recommend::where('id', $recommendId)->where('status', 1)->with(["mutual", "campusInfo"])->first();
        if (!$detail) {
            return new \stdClass();
        }
        $detail['publish_time'] = date('Y年m月d日', strtotime($detail['created_at']));//视频发布时间
        return $detail;
    }

    public function swiperList()
    {
        //20241029更改为全图片，且跳转到课程
        return Banner::where('status', 1)->limit(4)->offset(0)->orderBy('order', 'desc')->get();
        $condition = [
            'recommend.status' => 1,
        ];
        $page      = request('page') ?? 1;
        $size      = request('size') ?? 10;
        $offset    = ($page * $size) - $size;
        $field     = ['id', 'discover', 'title', 'video_url'];
        return Recommend::where($condition)->limit($size)->offset($offset)->orderBy('hot', 'desc')->get($field);
    }

    public function normalDetail()
    {
        $id     = request('r_id') ?? 0;
        $detail = Video::where('id', $id)->where('status', 1)->with(["campusInfo"])->first();
        if (!$detail) {
            return new \stdClass();
        }
        Video::where('id', $id)->increment('read_num', 1);
        $detail['intro']        = $detail['desc'];
        $detail['publish_time'] = date('Y年m月d日', strtotime($detail['created_at']));//视频发布时间
        return $detail;
    }
}
